package eppic.pkg;

import java.text.DecimalFormat;
import android.text.Editable;
import android.text.TextWatcher;
import android.widget.Toast;
import android.content.Context;
import android.widget.EditText;

public class rateTextWatcher implements TextWatcher {
	
	public Context context;
	public int newPos;
	public EditText rate;
	
	public rateTextWatcher(Context context, EditText rate)
	{
		this.context = context;
		this.rate = rate;
	}
	
	@Override
	public void afterTextChanged(Editable s) {
		
		if(s.length() > 11)
		{
			Toast.makeText(this.context, "You don't make that much. \n (Limit Exceeded)", Toast.LENGTH_LONG).show();
			this.rate.setText("$0.00");
		}
		else
		{
			String unformatted = s.toString();
			
			if(unformatted.charAt(0) != '$')
			{
				char badPlacement = unformatted.charAt(0);
				unformatted = unformatted.substring(1, unformatted.length());
				unformatted += badPlacement;
			}
			
			int dotPos = unformatted.lastIndexOf(".");
			
			if(unformatted.length() > dotPos+3)
			{
				DecimalFormat twoDForm = new DecimalFormat("#.##");
				char newDigit = unformatted.charAt(unformatted.length()-1);
				float value = new Float(unformatted.substring(1, unformatted.length()-1));
		        Double rate = Double.valueOf(twoDForm.format(value*10));
		        CharSequence formatted = "$"+rate+newDigit;
		        //s.clear();
		        this.rate.setText(formatted);
		        
			}
		}
				
	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// TODO Auto-generated method stub
		
	}


}